<template>
  <view class="index-page">
    <image class="page-bg" src="/static/images/bg.png" mode="aspectFill" />
    <CustomNavbar title="服务大厅" />
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
      <!-- 用户账户卡片 -->
      <view class="user-card">
        <view class="user-box">
          <view class="user-header">
            <view class="user-info">
              <text class="phone">{{ userStore.maskedPhone }}</text>
              <view class="tag" v-if="!userStore.isVerified">
                <image src="/static/icons/icon-auth.png" alt=""/>
                未认证</view>
            </view>
            <view class="membership">
              <image class="crown" v-for="i in userStore.membershipLevel" :key="i" src="/static/icons/icon-xing.png" style="width: 48rpx; height: 48rpx;" />
            </view>
          </view>
          
          <view class="balance-section">
            <view class="balance-circle">
              <text class="balance-label">当前余额</text>
              <text class="balance-amount">{{ userStore.balance }}</text>
              <text class="balance-unit">元</text>
            </view>
          </view>
        </view>

      
      <view class="account-stats">
        <view class="stat-item">
          <text class="stat-value">{{ userStore.usedData }}GB</text>
          <text class="stat-label">已用流量</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ userStore.usedCharge }}元</text>
          <text class="stat-label">已用话费</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ userStore.voiceBalance }}分钟</text>
          <text class="stat-label">语音余量</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ userStore.points }}</text>
          <text class="stat-label">可用积分</text>
        </view>
      </view>
    </view>
    
    <!-- 快捷服务 -->
    <view class="quick-services">
      <view class="service-item" @click="navigateToRecharge">
        <view class="service-icon">
          <image src="/static/icons/icon-home1.png" alt=""/>
        </view>
        <text class="service-label">充值话费</text>
      </view>
      <view class="service-item" @click="navigateTo('/pages/bill/bill')">
        <view class="service-icon">
          <image src="/static/icons/icon-home2.png" alt=""/>
        </view>
        <text class="service-label">我的账单</text>
      </view>
      <view class="service-item" @click="navigateTo('/pages/package/package')">
        <view class="service-icon">
          <image src="/static/icons/icon-home3.png" alt=""/>
        </view>
        <text class="service-label">套餐余量</text>
      </view>
      <view class="service-item" @click="navigateTo('/pages/balance-detail/balance-detail')">
        <view class="service-icon">
          <image src="/static/icons/icon-home4.png" alt=""/>
        </view>
        <text class="service-label">余额明细</text>
      </view>
    </view>
    
    <!-- 热门服务 -->
    <view class="section">
      <view class="section-title">热门服务</view>
      <view class="service-grid">
        <view class="grid-item" @click="navigateTo('/pages/bill/bill')">
          <view class="grid-icon"><image src="/static/icons/icon-home5.png" alt=""/></view>
          <text class="grid-label">我的账单</text>
        </view>
        <view class="grid-item" @click="navigateTo('/pages/package/package')">
          <view class="grid-icon"><image src="/static/icons/icon-home6.png" alt=""/></view>
          <text class="grid-label">套餐余量</text>
        </view>
        <view class="grid-item">
          <view class="grid-icon"><image src="/static/icons/icon-home7.png" alt=""/></view>
          <text class="grid-label">基础服务开通</text>
        </view>
        <view class="grid-item" @click="navigateToDigitalService">
          <view class="grid-icon"><image src="/static/icons/icon-home8.png" alt=""/></view>
          <text class="grid-label">数字人客服</text>
        </view>
        <view class="grid-item" @click="navigateTo('/pages/balance-detail/balance-detail')">
          <view class="grid-icon"><image src="/static/icons/icon-home9.png" alt=""/></view>
          <text class="grid-label">余额明细</text>
        </view>
        <view class="grid-item">
          <view class="grid-icon"><image src="/static/icons/icon-home10.png" alt=""/></view>
          <text class="grid-label">缴费查询</text>
        </view>
        <view class="grid-item" @click="navigateTo('/pages/detail-query/detail-query')">
          <view class="grid-icon"><image src="/static/icons/icon-home11.png" alt=""/></view>
          <text class="grid-label">详单查询</text>
        </view>
        <view class="grid-item" @click="navigateToInternationalRoaming">
          <view class="grid-icon"><image src="/static/icons/icon-home12.png" alt=""/></view>
          <text class="grid-label">国际漫游</text>
        </view>
      </view>
    </view>
    
    <!-- 猜你喜欢 -->
    <view class="section">
      <view class="section-title">猜你喜欢</view>
      <view class="recommend-area">
        <text class="empty-text">暂无推荐内容</text>
      </view>
    </view>
    </view>
    <CustomTabBar current="/pages/index/index" />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import CustomNavbar from '@/components/CustomNavbar.vue'
import CustomTabBar from '@/components/CustomTabBar.vue'
import { api } from '@/utils/api.js';
import { encryptByDESModeCBCUtf8to64 } from '@/utils/crypto.js';

const statusBarHeight = ref(0)
const navBarHeight = ref(88) // 默认值：状态栏(44) + 导航栏(44)

// 在setup函数内部调用useUserStore()，确保Pinia已初始化
const userStore = useUserStore()

onMounted(() => {
  // 使用新的 API 获取窗口信息
  const windowInfo = uni.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight || 0
  navBarHeight.value = statusBarHeight.value + 64

  

  var key = "holly12345678Az@";
  var iv = "0392039203920300";
  let cs = "19990409544";
  // let cs = "19990409544";18999930691；18129382111
  
  try {
    var param = encryptByDESModeCBCUtf8to64(cs, key, iv);
    console.log('✅ 加密后的数据:', param)
    
    // 存储加密后的手机号，供后续接口使用
    // uni.setStorageSync('wxphone', param)
    console.log('✅ 已存储加密后的手机号到 wxphone')
    
    // testRequest(param)
  } catch (error) {
    console.error('❌ 加密失败，无法继续:', error)
    // 如果加密失败，可以尝试使用明文（仅用于调试）
    // uni.setStorageSync('wxphone', cs)
  }
  // uni.setStorageSync('wxphone', '')

  // const muserInfo = {
  //       // token: loginRes.data.token || loginRes.data.accessToken || '',
  //       openid:  "o2ZW7jo6N_oRDXYQ-k70smtXWo_U",
  //       // phone: loginRes.data.phone || '',
  //       type: "wechat_oauth", // 标识为微信H5授权登录
  //     };

  //     // 更新用户状态
  //     userStore.isLoggedIn = true;
  //     userStore.openid = muserInfo.openid;

  //     // 保存到本地存储
  //     uni.setStorageSync("userInfo", muserInfo);
  

  const userInfo = uni.getStorageSync("userInfo");
  // #ifdef H5
  if (!userInfo.openid) {
    uni.navigateTo({ url: '/pages/login/login' })
    return
  }

  // #endif

  // #ifndef H5
  if (!uni.getStorageSync('wxphone')) {
    uni.navigateTo({ url: '/pages/login/login' })
    return
  }
  // #endif
  

  
  // if (!uni.getStorageSync('wxphone')) {
  // if (!userInfo.openid) {
  //   uni.navigateTo({ url: '/pages/login/login' })

  //   // let isWX = isWechat()
	// 	// 	if (isWX) {
	// 	// 		getWXCode()
	// 	// 	} else {
	// 	// 		// uni.navigateTo({
	// 	// 		// 	url: '/pages/index/index'
	// 	// 		// });
	// 	// 	}


  // }else{

    //查询套餐余量
    uResource()
    //实时费用查询-已用话费
    queryRealTimeBill()
    //查询余额
    queryBalance()
    //查询套餐等级
    queryStartLevelInfo()

  // }


  // wx.getStorageSync('wxphone','uws7810zmiyjSSXvi5I3sg==')

  

})



const getWXCode = () => {
  api.wechatAuth({
    uri:'https://kf.xj.189.cn/xcxchat/#/pages/auth/auth',
  }).then(res => {
    console.log('22222222成功 == ',res)

    let code = getQueryVariable('code'); //是否存在code
    console.log('code == ',code)
    if(code) {
      console.log('code == ',code)

      api.getOpenId(
        code
        // '033cfnFa14eqGK0J1YHa1jcsJg4cfnFa'
      ).then(res => {
        console.log('33333333成功 == ',res)
      }).catch(err => {
        console.log('44444444失败 == ',err)
      })
      
    }else{
      window.location.href = res.data
    }

    // window.location.href = res.data
  }).catch(err => {
    console.log('11111111失败 == ',err)
  })


}


const getQueryVariable = (variable) =>{
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return (false);
    }

const getUrlCode = () => {
				// 截取url中的code方法
				var url = location.search;
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
					}
				}
				return theRequest;
			}


// 判断是否为微信环境
			const isWechat = ()=> {
				var ua = navigator.userAgent.toLowerCase()
 
				var isWXWork = ua.match(/wxwork/i) == 'wxwork'
 
				var isWeixin = !isWXWork && ua.match(/MicroMessenger/i) == 'micromessenger'
				return isWeixin
 
			}


//查询套餐余量
const uResource = async (param) => {
  api.queryUResourc({}).then(res => {
    
    const data = res.data
    console.log('查询套餐余量:', JSON.stringify(data))
    //语音余量
    userStore.voiceBalance = (data.yy_sy && data.yy_sy >=100000000)?'本地不限量':data.yy_sy
    userStore.usedData = data.ll_use;//流量已用
  
  }).catch(err => {
    console.error('查询套餐余量失败:', err)
  })
}

//实时费用查询-已用话费
const queryRealTimeBill = async () => {
  api.realTimeBillQuery({}).then(res => {
    console.log('实时账单查询:', JSON.stringify(res))
    userStore.usedCharge = res.data.sumCharge;//已用话费
  }).catch(err => {
    console.error('实时账单查询失败:', err)
  })
}

//查询余额
const queryBalance = async () => {
  api.queryBalance({}).then(res => {
    console.log('查询余额:', JSON.stringify(res))
    // 使用updateBalance方法更新余额，formattedBalance会自动计算
    userStore.balance = res.data.total;
    // userStore.updateBalance(1111);
  }).catch(err => {
    console.error('查询余额失败:', err)
  })
}

//查询套餐等级
const queryStartLevelInfo = async () => {
  api.queryStartLevelInfo({}).then(res => {
    console.log('查询套餐等级:', JSON.stringify(res))
    // userStore.startLevel = res.data.startLevel;//套餐等级
    // userStore.membershipLevel = res.data.starLevel;//套餐等级
    if(res.data.starLevel == "3100"){
      userStore.membershipLevel = 1;//套餐等级
    }else if(res.data.starLevel == "3200"){
      userStore.membershipLevel = 2;//套餐等级
    }else if(res.data.starLevel == "3300"){
      userStore.membershipLevel = 3;//套餐等级
    }else if(res.data.starLevel == "3400"){
      userStore.membershipLevel = 4;//套餐等级
    }else if(res.data.starLevel == "3500"){
      userStore.membershipLevel = 5;//套餐等级
    }else if(res.data.starLevel == "3600"){
      userStore.membershipLevel = 6;//套餐等级
    }else if(res.data.starLevel == "3700"){
      userStore.membershipLevel = 7;//套餐等级
    }
    
  }).catch(err => {
    console.error('查询套餐等级失败:', err)
  })
}

// 加密函数已从 @/utils/crypto.js 导入，无需重复定义

const testRequest = async (param) => {

  api.realTimeBillQuery({}).then(res => {
    console.log('实时账单查询1111 = :', JSON.stringify(res))
  }).catch(err => {
    console.error('实时账单查询失败:', err)
  })

  //  const res = await uni.request({
  //   url: 'https://kf.xj.189.cn/xjwechat/wxCustomer/realTimeBillQuery',
  //   method: 'POST',
  //   data: {
  //     wxphone: param
  //   }
  // })
  // console.log('查询余额:', JSON.stringify(res))
}

// 检查是否已登录
const isLoggedIn =  () => {
  return !!uni.getStorageSync('token');
}

const navigateTo = (url) => {
  uni.navigateTo({ url })
}

/**
 * 通用外链接跳转方法
 * 支持 H5 和小程序平台
 * @param {string} url - 目标网页地址（必须是完整的 https:// 或 http:// 开头的 URL）
 * @param {string} title - 小程序中 web-view 页面的标题（可选，默认为"网页"）
 */
const navigateToExternalUrl = (url, title = '网页') => {
  if (!url) {
    console.error('navigateToExternalUrl: url 参数不能为空')
    uni.showToast({
      title: '链接地址不能为空',
      icon: 'none',
      duration: 2000
    })
    return
  }

  // 确保 URL 是完整的地址
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    console.error('navigateToExternalUrl: url 必须是完整的 http:// 或 https:// 地址')
    uni.showToast({
      title: '链接地址格式错误',
      icon: 'none',
      duration: 2000
    })
    return
  }

  // #ifdef H5
  // H5 端：直接使用 window.location 跳转
  try {
    window.location.href = url
  } catch (error) {
    console.error('H5 跳转失败:', error)
    uni.showToast({
      title: '跳转失败',
      icon: 'none',
      duration: 2000
    })
  }
  // #endif

  // #ifdef MP-WEIXIN
  // 微信小程序：通过 web-view 组件打开外部链接
  // 注意：需要在微信公众平台配置业务域名 kf.xj.189.cn
  uni.navigateTo({
    url: `/pages/link/link?lurl=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}`,
    success: (res) => {
      console.log('跳转到 web-view 页面成功:', res)
    },
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '跳转失败，请检查业务域名配置',
        icon: 'none',
        duration: 2000
      })
    }
  })
  // #endif

  // #ifdef APP-PLUS
  // App 端：使用 plus.runtime.openURL 打开外部浏览器
  try {
    plus.runtime.openURL(url, (err) => {
      if (err) {
        console.error('App 打开外部链接失败:', err)
        uni.showToast({
          title: '打开链接失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  } catch (error) {
    console.error('App 跳转异常:', error)
  }
  // #endif
}

// 跳转到充值话费
const navigateToRecharge = () => {
  navigateToExternalUrl('https://kf.xj.189.cn/xjwechat/serviceHall/getzxkfurl', '充值话费')
}

// 跳转到国际漫游
const navigateToInternationalRoaming = () => {
  navigateToExternalUrl('https://kf.xj.189.cn/xjwechat/serviceHall/internationalRoaming', '国际漫游')
}

// 跳转到数字人客服
const navigateToDigitalService = async () => {
  try {
    // 获取手机号
    const userInfo = uni.getStorageSync('userInfo')
    const phone = userStore.phone || userInfo?.phone || '18124058091'
    
    if (!phone) {
      uni.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    // 显示加载提示
    uni.showLoading({
      title: '加载中...',
      mask: true
    })
    
    // 调用接口获取数字人客服URL
    const res = await api.getSzrUrl(phone)
    
    uni.hideLoading()
    
    if (res.code === 200 && res.msg) {
      const targetUrl = res.msg
      
      // 跳转到返回的URL
      // #ifdef H5
      window.location.href = targetUrl
      // #endif
      
      // #ifdef MP-WEIXIN
      // 小程序中需要通过 web-view 打开外部链接
      // 注意：需要在 manifest.json 中配置业务域名 szr.ai.chinatelecom.cn
      // 使用相对路径跳转到包含 web-view 的页面
      uni.navigateTo({
        url: targetUrl,
        success: () => {
          console.log('跳转到 web-view 页面成功')
        },
        fail: (err) => {
          console.error('跳转失败:', err)
          // 如果相对路径失败，尝试绝对路径
          uni.navigateTo({
            url: `/pages/link/link?lurl=${encodeURIComponent(targetUrl)}`,
            fail: (err2) => {
              console.error('绝对路径跳转也失败:', err2)
              uni.showToast({
                title: '跳转失败，请检查配置',
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      })
      // #endif
      
      // #ifdef APP-PLUS
      plus.runtime.openURL(targetUrl)
      // #endif
    } else {
      throw new Error(res.msg || '获取客服链接失败')
    }
  } catch (error) {
    uni.hideLoading()
    console.error('跳转数字人客服失败:', error)
    uni.showToast({
      title: error.message || '获取客服链接失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
}
</script>

<style scoped>
.index-page {
   
  position: relative;
  z-index: 1;
  overflow: hidden;
}

.page-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -1;
  pointer-events: none;
  object-fit: cover;
}

.page-content {
  position: relative;
  z-index: 2;
   
  padding-bottom: 130rpx;
}

.user-card {
  background: #fff;
  border-radius: 30rpx;
  margin: 40rpx;
  padding: 24rpx 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 2;
  /* height: 300rpx; */
}
.user-box{
  display: flex;
  /* align-items: center; */
  margin-bottom: 20rpx;
}

.user-header {
  /* display: flex;
  justify-content: space-between;
  align-items: center; */
  /* margin-bottom: 40rpx; */
  margin-top: 24rpx;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.phone {
  color: rgba(51, 51, 51, 1);
font-family: Inter;
font-size: 32rpx;
font-weight: 700;
line-height: 38rpx;
}

.tag {
  background: #F0F0F0;
  color: #999;
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}
.tag image{
width: 20rpx;
height: 16rpx
}

.membership {
  display: flex;
  gap: 8rpx;
}

.crown {
  font-size: 32rpx;
}

.balance-section {
  padding: 24rpx;
  margin-top: -88rpx;
  background: #fff;
  border-radius: 50%;
}

.balance-circle {
  background: #fff;
  width: 180rpx;
    height: 180rpx;
  /* padding: 24rpx; */
  border: 16.74rpx solid rgba(205, 236, 195, 1);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.balance-label {
  color: rgba(51, 51, 51, 1);
font-family: HarmonyOS Sans SC;
font-size: 20rpx;
font-weight: 400;
line-height: 24rpx;
  margin-bottom: 10rpx;
}

.balance-amount {
  color: rgba(61, 193, 44, 1);
font-family: HarmonyOS Sans SC;
font-size: 32rpx;
font-weight: 700;
line-height: 38rpx;
}

.balance-unit {
  color: rgba(51, 51, 51, 1);
font-family: HarmonyOS Sans SC;
font-size: 20rpx;
font-weight: 400;
line-height: 24rpx;
  margin-top: 5rpx;
}

.account-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
    align-items: center;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

.quick-services {
  display: flex;
  justify-content: space-around;
  /* padding: 30rpx; */
  /* background: #fff; */
  margin: 0 30rpx 30rpx;
  border-radius: 20rpx;
  position: relative;
  z-index: 2;
}

.service-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.service-icon {
  width: 84rpx;
  height: 84rpx;
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 48rpx;
  margin-bottom: 15rpx;
}
.service-icon image{
  width: 84rpx;
  height: 84rpx;
}

.service-icon.green {
  background: #E8F5E9;
}

.service-icon.blue {
  background: #E3F2FD;
}

.service-icon.light-blue {
  background: #E0F7FA;
}

.service-icon.orange {
  background: #FFF3E0;
}

.service-label {
  font-size: 24rpx;
  color: #333;
}

.section {
  margin: 40rpx;
}

.section-title {
  color: rgba(51, 51, 51, 1);
font-family: HarmonyOS Sans SC;
font-size: 32rpx;
font-weight: 700;
line-height: 38rpx;
  margin-bottom: 24rpx;
}

.service-grid {
  display: flex;
    flex-wrap: wrap;
    gap: 26rpx;
     background: rgba(255, 255, 255, 1);
    padding: 32rpx;
    border-radius: 24rpx;
    position: relative;
}

.grid-item {
  width: calc(25% - 22.5rpx);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.grid-icon {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40rpx;
  margin-bottom: 15rpx;
}
.grid-icon image {
  width: 64rpx;
  height: 64rpx;
}

.grid-label {
  font-size: 24rpx;
  color: #666;
  text-align: center;
}

.recommend-area {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  text-align: center;
  position: relative;
  z-index: 2;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}
</style>

